package com.wenye.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wenye.Util.JWTUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PageController {
    @GetMapping("/index")
    public String index(HttpServletRequest request, Model model){
        Map<String, Object> map = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        String token = "";
        for(Cookie a:cookies) {
            System.out.println(a.getName());
            if(a.getName().equals("token")){
                System.out.println("TOKEN==="+token);
                token=a.getValue();
            }
        }
        if(token==null)
            return "";
        DecodedJWT verify = JWTUtil.Verify(token);
        System.out.println(verify.getClaim("ID").asString());
        System.out.println(verify.getClaim("username").asString());
        model.addAttribute("username",verify.getClaim("username").asString());
        map.put("state",true);
        map.put("msg","认证成功");
        return "index";
    }

    @PostMapping("/loginout")
    public String loginOut(HttpServletResponse response){
        Cookie cookie = new Cookie("token", "null");
        cookie.setDomain("localhost");
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:index";
    }
}
